using Microsoft.AspNetCore.Mvc;
using UserManagement.Data;
using UserManagement.Models;
using UserManagement.Services;

namespace UserManagement.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UsersController(IUserService userService, IExcelExportService excelExportService, AppDbContext appDbContext)
    : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetAllUsers() => Ok(await userService.GetAllUsersAsync());

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser(int id) => Ok(await userService.GetUserAsync(id));

    [HttpPost]
    public async Task<IActionResult> AddUser(User user)
    {
        await userService.AddUserAsync(user);
        return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
    }
    
    [HttpPost("batch")]
    public async Task<IActionResult> AddUsers(List<User> users)
    {
        await userService.AddUsersAsync(users);
        return CreatedAtAction(nameof(GetAllUsers), null, users);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateUser(int id, User user)
    {
        await userService.UpdateUserAsync(id, user);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteUser(int id)
    {
        await userService.DeleteUserAsync(id);
        return NoContent();
    }

    [HttpGet("export")]
    public IActionResult ExportUsers()
    {
        var users = appDbContext.Users.ToList();
        byte[] fileBytes = excelExportService.ExportUsers(users);
        return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "users.xlsx");
    }
}